package los.kael.fixcss;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 传入StringBuffer 并清除冗余和格式化
 * </p>
 * 
 * @author kael
 * @filename ClearAndFormat.java
 * @version 0.1 2011-10-26 下午10:17:35
 */
public class ClearAndFormat {
	private StringBuffer sb = new StringBuffer();
	private String method = "line";

	/**
	 * <p>
	 * 返回处理结果
	 * </p>
	 * 
	 * @return StringBuffer
	 */
	public StringBuffer getSb() {
		return sb;
	}

	/**
	 * <p>
	 * 传入要处理的 StringBuffer
	 * </p>
	 * 
	 * @param sb
	 */
	public ClearAndFormat(StringBuffer sb) {
		this.sb = sb;
	}

	/**
	 * <p>
	 * 处理注释
	 * </p>
	 * 
	 * @return 返回其本身this
	 */
	public ClearAndFormat ClearAnnotation() {
		String src = "";
		String ant = "";
		StringBuffer tempSb = new StringBuffer();
		boolean flag = false;
		for (int i = 0, len = sb.length(); i < len; i++) {
			if (flag) {
				ant += sb.charAt(i);
				// 注释结束
				if (ant.indexOf("*/") != -1) {
					flag = false;
					ant = "";
				}
			} else {
				src += sb.charAt(i);
				// 遇到注释
				if (src.indexOf("/*") != -1) {
					flag = true;
					src = src.replace("/*", "");
					tempSb.append(src);
					src = "";
				}
			}
		}
		sb = tempSb;
		return this;
	}

	/**
	 * <p>
	 * 清除空白
	 * </p>
	 * 
	 * @return
	 */
	public ClearAndFormat ClearSpace() {
		return ClearSpace(method);
	}

	/**
	 * <p>
	 * 处理空白
	 * </p>
	 * 
	 * @return
	 */
	public ClearAndFormat ClearSpace(String method) {
		char ch;
		String src = "";
		String space = "";
		StringBuffer tempSb = new StringBuffer();
		boolean flag = false;
		for (int i = 0, len = sb.length(); i < len; i++) {
			ch = sb.charAt(i);
			if (ch == '\n' || ch == '\r') {
				continue;
			}
			src += ch;
			if (!flag) {
				// if(method != "min" && method != "line" && ch == ','){
				// src += '\n';
				// }
				if (src.indexOf("{") != -1) {
					flag = true;
				}
			} else {
				if (src.indexOf("}") != -1) {
					flag = false;
					if (method == "min") {
						src = toMin(src);
					} else if (method == "line") {
						src = toLine(src);
					} else {
						src = toEasyRead(src);
					}
					tempSb.append(src);
					src = "";
				}
			}
			// 处理charset
			if (src.indexOf("@charset") != -1 && src.indexOf(";") != -1) {
				if (method == "min") {
					tempSb.append(src);
				} else {
					tempSb.append(src + "\n");
				}
				src = "";
			}
		}
		sb = tempSb;
		return this;
	}

	/**
	 * <p>
	 * 生成最小
	 * </p>
	 * 
	 * @return
	 */
	public ClearAndFormat MakeMin() {
		return ClearSpace("min");
	}

	/**
	 * <p>
	 * 生成最小
	 * </p>
	 * 
	 * @param src
	 * @return
	 */
	private String toMin(String src) {
		src = src.replace("\t", " ");
		src = src.replace(", ", ",");
		src = src.replace(" ,", ",");
		src = src.replace(": ", ":");
		src = src.replace(" :", ":");
		src = src.replace(" {", "{");
		src = src.replace("{ ", "{");
		src = src.replace(";}", "}");
		src = src.replace(" }", "}");
		src = src.replace("} ", "}");
		src = src.replace(" )", ")");
		src = src.replace(") ", ")");
		src = src.replace(" (", "(");
		src = src.replace("( ", "(");
		src = src.replace(" ;", ";");
		src = src.replace("; ", ";");
		src = src.trim();
		return src;
	}

	/**
	 * <p>
	 * 按行生成最小代码
	 * </p>
	 * 
	 * @param src
	 * @return
	 */
	private String toLine(String src) {
		src = src.replace("\t", " ");
		src = src.replace(", ", ",");
		src = src.replace(" ,", ",");
		src = src.replace(": ", ":");
		src = src.replace(" :", ":");
		src = src.replace(" {", "{");
		src = src.replace("{ ", "{");
		src = src.replace(";}", "}");
		src = src.replace(" }", "}");
		src = src.replace("} ", "}");
		src = src.replace(" )", ")");
		src = src.replace(") ", ")");
		src = src.replace(" (", "(");
		src = src.replace("( ", "(");
		src = src.replace(" ;", ";");
		src = src.replace("; ", ";");
		src = src.trim();
		src += '\n';
		return src;
	}

	/**
	 * <p>
	 * 生成最易于阅读的代码
	 * </p>
	 * 
	 * @param src
	 * @return
	 */
	private String toEasyRead(String src) {
		src = src.replace("\t", " ");
		src = src.replace(", ", ",");
		src = src.replace(" ,", ",");
		src = src.replace(": ", ":");
		src = src.replace(" :", ":");
		src = src.replace(" {", "{");
		src = src.replace("{ ", "{");
		src = src.replace(";}", "}");
		src = src.replace(" }", "}");
		src = src.replace("} ", "}");
		src = src.replace(" )", ")");
		src = src.replace(") ", ")");
		src = src.replace(" (", "(");
		src = src.replace("( ", "(");
		src = src.trim();
		src = src.replace("{", "{\n    ");
		src = src.replace(":", ": ");
		src = src.replace(";", ";\n    ");
		src = src.replace("}", ";\n}\n\n");
		return src;
	}

	/**
	 * <p>
	 * 获取所有hack
	 * </p>
	 * 
	 * @return
	 */
	public ClearAndFormat GetHack() {
		char ch;
		String src = "";
		// 存储正常代码
		StringBuffer code = new StringBuffer();
		// 存储hack代码
		StringBuffer hack = new StringBuffer();
		// key保存标签 类 等
		String key = "";
		// value保存属性和值
		String value = "";
		String temp;
		// 正常代码(行)
		String codeStr = "";
		// hack代码(行)
		String hackStr = "";
		// 迭代器
		Iterator<String> it;
		int index;
		hack.append("\n/* hack */\n");
		for (int i = 0, len = sb.length(); i < len; i++) {
			ch = sb.charAt(i);
			src += ch;
			// 逐行处理
			if (ch == '\n') {
				index = src.indexOf("{");
				if (index != -1) {
					// 获取标签
					key = src.substring(0, index + 1);
					// 获取属性和值
					value = src.substring(index + 1, src.length());
					// 将属性和值依次存入list并逐个处理
					it = makeValueList(value).iterator();
					hackStr = "";
					codeStr = "";
					while (it.hasNext()) {
						temp = it.next().toString().trim();
						temp = temp.replace("\t", " ");
						while(temp.indexOf(" :") != -1){
							temp = temp.replace(" :", ":");
						}
						if (temp.startsWith("_") /* IE6 */
								|| temp.startsWith("*") /* IE67 */
								|| temp.indexOf("\0") != -1 /* IE678 */
								|| temp.indexOf("!important") != -1 /* IE6 */
								|| temp.indexOf("zoom:") != -1 /* IE */
								|| temp.indexOf("word-break:") != -1 /* IE */
								|| temp.indexOf("word-wrap:") != -1 /* IE */
								|| temp.indexOf("behavior:") != -1 /* IE */
								|| temp.indexOf("filter:") != -1 /* IE */
								|| temp.indexOf("-webkit-") != -1 /* Chrome Safari */
								|| temp.indexOf("-moz-") != -1 /* FireFox */
								|| temp.indexOf("-O-") != -1 /* Opera */
								|| temp.indexOf("-pie-") != -1 /* IE */
								|| temp.indexOf("shadow") != -1 /* 阴影 */
								|| temp.indexOf("border-radius") != -1 /* 圆角 */
								|| temp.indexOf("linear-gradient") != -1 /* Pie 渐变 */
						) {
							hackStr += temp;
						} else {
							codeStr += temp;
						}
					}
					if (codeStr != "") {
						code.append(key + codeStr + "}\n");
					}
					if (hackStr != "") {
						hack.append(key + hackStr + "}\n");
					}
				} else {
					code.append(src);
				}
				src = "";
			}

		}
		code.append(hack);
		sb = code;
		return this;
	}

	/**
	 * <p>
	 * 获取所有的color
	 * </p>
	 * 
	 * @return
	 */
	public ClearAndFormat GetColors() {
		char ch;
		String src = "";
		// 存储正常代码
		StringBuffer code = new StringBuffer();
		// 存储color代码
		StringBuffer color = new StringBuffer();
		// key保存标签 类 等
		String key = "";
		// value保存属性和值
		String value = "";
		String temp;
		// 正常代码(行)
		String codeStr = "";
		// color代码(行)
		String colorStr = "";
		// 迭代器
		Iterator<String> it;
		int index;
		color.append("\n/* color */\n");
		for (int i = 0, len = sb.length(); i < len; i++) {
			ch = sb.charAt(i);
			src += ch;
			// 逐行处理
			if (ch == '\n') {
				index = src.indexOf("{");
				if (index != -1) {
					// 获取标签
					key = src.substring(0, index + 1);
					// 获取属性和值
					value = src.substring(index + 1, src.length());
					// 将属性和值依次存入list并逐个处理
					it = makeValueList(value).iterator();
					colorStr = "";
					codeStr = "";
					while (it.hasNext()) {
						temp = it.next().toString().trim();
						temp = temp.replace("\t", " ");
						while(temp.indexOf(" :") != -1){
							temp = temp.replace(" :", ":");
						}
						if (temp.indexOf("color") != -1 /* color */
							|| (temp.indexOf("background") != -1 
								&& temp.indexOf("background-position") == -1
							) /* background */
							|| (temp.indexOf("border") != -1 
								&& temp.indexOf("border-spacing") == -1 
								&& temp.indexOf("border-collapse") == -1 
								&& temp.indexOf("border:none") == -1 
								&& temp.indexOf("border:0") == -1
							) /* border */
							|| temp.indexOf("shadow") != -1 /* 阴影 */
							|| temp.indexOf("border-radius") != -1 /* 圆角 */
							|| temp.indexOf("linear-gradient") != -1 /* 渐变 */
							|| temp.indexOf("behavior") != -1 /* IE */
							|| temp.indexOf("filter") != -1 /* IE */
						) {
							colorStr += temp;
						} else {
							codeStr += temp;
						}
					}
					if (codeStr != "") {
						code.append(key + codeStr + "}\n");
					}
					if (colorStr != "") {
						color.append(key + colorStr + "}\n");
					}
				} else {
					code.append(src);
				}
				src = "";
			}

		}
		code.append(color);
		sb = code;
		return this;
	}

	/**
	 * <p>
	 * 获取各个属性值到List中
	 * </p>
	 * 
	 * @param value
	 * @return
	 */
	private List<String> makeValueList(String value) {
		List<String> list = new ArrayList<String>();
		if (value.indexOf(";}") == -1) {
			value = value.replace("}", ";}");
		}
		while (value.indexOf(";") != -1) {
			list.add(value.substring(0, value.indexOf(";") + 1));
			value = value.substring(value.indexOf(";") + 1);
		}
		return list;
	}

}
